package com.xtgg.baby;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.device.AddBabyActivity;
import com.xtgg.login.LoginActivity;
import com.xtgg.main.MainActivity;
import com.xtgg.main.MainPageActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;

import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BabyBoundListActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	JSONArray mArray = null;
	int mSelected = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_baby_bound_list);

		((TextView) findViewById(R.id.center)).setText("匹配宝宝");
		((Button) findViewById(R.id.right))
				.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.ic_add_device, 0);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
		
		((Button)findViewById(R.id.left)).setText("取消");
		((Button)findViewById(R.id.left)).setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				mSelected = arg2 - 1;
				mAdapter.notifyDataSetChanged();
			}
		});

		sendHttpRequest();
	}

	class MyAdapter extends BaseAdapter{
		public int getCount() {
			return mArray != null ? mArray.size() : 0;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_bound_baby, null);
				foodHold.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			JSONObject item = mArray.getJSONObject(position);
			foodHold.name.setText(item.getString("childname"));
			
			foodHold.name.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			if(mSelected == position) foodHold.name.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_select, 0);
			return convertView;
		}
	}

	public final class FoodHolder {
		public TextView name;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			showMainView();
			break;

		case R.id.right:
			Intent intent = new Intent(this,AddBabyActivity.class);
			intent.putExtra("info", getIntent().getStringExtra("info"));
			intent.putExtra("deviceid", getIntent().getStringExtra("deviceid"));
			startActivity(intent);
			break;
			
		case R.id.login:
			sendBoundHttpRequest();
			break;
		}
	}

	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mArray = JSON.parseObject(response).getJSONArray("data");
					mAdapter.notifyDataSetChanged();
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				}
				else
				{
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "getMyChildList");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
	
	private void sendBoundHttpRequest() {
		if(mSelected < 0 || mArray == null)
		{
			ToastUtil.showToastWithAlertPic("请选择宝宝");
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					showToast("宝宝设备绑定成功");
					
					showMainView();
					
					JSONObject obj = JSON.parseObject(getIntent().getStringExtra("info"));
					BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
							.getRemoteDevice(obj.getString("address"));
					localBluetoothDevice.connectGatt(BabyBoundListActivity.this, false, ((DemoApp)getApplicationContext()).mGattCallback);
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				}else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};
		
		JSONObject item = mArray.getJSONObject(mSelected);
		
		RequestParams params = new RequestParams();
		params.put("act", "relChild");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("deviceid", getIntent().getStringExtra("deviceid"));
		params.put("childid", item.getString("childid"));
		params.put("childname", item.getString("childname"));
		params.put("nickname", item.getString("nickname"));
		params.put("sex", item.getString("sex"));
		params.put("birth", item.getString("birth"));
		params.put("description", item.getString("description"));
		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}
}
